<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form-model ref="form" :model="mdl" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-form-model-item :label="i18n('form.gategory','分类')" prop="gategory">
                        <rx-category-select v-model="mdl.gategory" cat-key="SYSTEM" :isGrant="true" ></rx-category-select>
                    </a-form-model-item>
                    <a-form-model-item :label="i18n('form.name','名称')" prop="name">
                        <a-input :placeholder="i18n('form.name','名称','input')" v-model="mdl.name"/>
                    </a-form-model-item>

                    <a-form-model-item :label="i18n('form.type','类型')" prop="type">
                        <a-select :options="typeDef" v-model="mdl.type" @change="clearSetting"></a-select>
                    </a-form-model-item>

                    <a-form-model-item :label="i18n('form.storeType','存储类型')" prop="storeType" v-show="mdl.type">
                        <a-select :options="storeDef" v-model="mdl.storeType" @change="clearSetting"></a-select>
                    </a-form-model-item>

                    <a-form-model-item :label="i18n('form.database','资源库')" v-if="mdl.storeType=='database'">
                        <a-select :options="databases" v-model="setting.database"></a-select>
                    </a-form-model-item>
                    <a-form-model-item :label="i18n('form.job','作业')" v-if="mdl.storeType=='database'">
                        <a-tree-select :replaceFields="replaceFields" v-model="setting.job" :treeData="jobTree" @change="jobChange" allowClear></a-tree-select>
                    </a-form-model-item>

                    <a-form-model-item :label="i18n('form.job','作业')" class="ainpust" v-if="mdl.storeType=='file'">
                        <a-input :disabled="true"  v-model="fileSetting.fileName" style="width: 90%"></a-input>
                        <a-button  @click="onClick" ><a-icon type="folder-open" /></a-button>
                        <a-input id="inputid" type="file" @change="selectFile"></a-input>
                    </a-form-model-item>

                    <a-form-model-item :label="i18n('form.valConf','变量配置')" v-show="mdl.type">
                        <a-row >
                            <div style="text-align: right;">
                                <a-button-group >
                                    <a-button type="primary" @click="addParame()">
                                        <a-icon type="plus"></a-icon>
                                    </a-button>
                                    <a-button @click="removeParames()">
                                        <a-icon type="minus"></a-icon>
                                    </a-button>
                                </a-button-group>
                            </div>
                        </a-row>
                        <a-table :dataSource="parameterList" :pagination="false" rowKey="idx_" :rowSelection="rowSelection">
                            <a-table-column :title="i18n('form.paramName','参数名')" dataIndex="name">
                                <template slot-scope="text, record">
                                    <a-input v-model="record.name"></a-input>
                                </template>
                            </a-table-column>
                            <a-table-column :title="i18n('form.paramValue','参数值')" dataIndex="value">
                                <template slot-scope="text, record">
                                    <a-input v-model="record.value"></a-input>
                                </template>
                            </a-table-column>
                        </a-table>
                    </a-form-model-item>

                </a-form-model>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import SysKettleDefApi from '@/api/system/core/sysKettleDef'
import {RxDialog, BaseFormModel,Util,GridMixin} from "@lowcode/jpaas-common-lib";
import SysKettleDbdefApi from '@/api/system/core/sysKettleDbdef';
export default {
    name: 'SysKettleDefEdit',
    mixins: [BaseFormModel,GridMixin],
    components: {
        RxDialog,
    },
    data() {
        return {
            typeDef: [{label: this.i18n('form.job','作业'), value: "job"}, {label: this.i18n('form.transformation','转换'), value: "transformation"}],
            storeDef: [{label: this.i18n('form.database','资源库'), value: "database"}, {label: this.i18n('form.file','文件'), value: "file"}],
            rules: {
                name: [{required: true, message: this.i18n('form.name','请输入名称','input'), trigger: 'change'}],
                storeType: [{required: true, message: this.i18n('form.storeType','请选择存储类型','input'), trigger: 'change'}],
                gategory: [{required: true, message: this.i18n('form.gategory','请选择分类','select'), trigger: 'change'}],
                storeSetting: [{required: false, message: this.i18n('form.storeSetting','请输入存储设定','input'), trigger: 'change'}],
                type: [{required: true, message: this.i18n('form.type','请选择类型','select'), trigger: 'change'}],
                parameters: [{required: false, message: this.i18n('form.type','请选择类型','select'), trigger: 'change'}],
            },
            replaceFields:{children:'children', title:'text', key:'text', value: 'text' },
            setting:{
                database:"",
                job:"",
                directory:""
            },
            fileSetting:{
                fileName:"",
                fileId:""
            },
            databases:[],
            jobs:[],
            jobTree:[],
            parameterList:[],
            selectedRowKeys:[],
        }
    },
    computed: {
        rowSelection() {
            return {
                selectedRowKeys: this.selectedRowKeys,
                onChange: this.onSelectChange
            }
        },
    },
    created() {
        this.getDatabases();
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"SysKettleDef",key);
        },
        onClick(){
            document.getElementById('inputid').click();
        },
        get(id) {
            return SysKettleDefApi.get(id);
        },
        save() {
            if(this.mdl.storeType=="database"){
                this.mdl.storeSetting=JSON.stringify(this.setting);
            }else if(this.mdl.storeType=="file"){
                this.mdl.storeSetting=JSON.stringify(this.fileSetting);
            }else {
                this.mdl.storeSetting="";
            }
            //保存参数
            var parameters=[];
            for (var i = 0; i < this.parameterList.length; i++) {
                parameters.push({
                    name:this.parameterList[i].name,
                    value:this.parameterList[i].value
                });
            }
            this.mdl.parameters=JSON.stringify(parameters);
            return SysKettleDefApi.save(this.mdl);
        },
        //获取资源库
        getDatabases(){
            SysKettleDbdefApi.getAllByStatus("1").then(res => {
                if(res.success){
                    this.databases=[];
                    var data=res.data;
                    for (var i = 0; i < data.length; i++) {
                        this.databases.push({
                            label: data[i].name,
                            value: data[i].id
                        });
                    }
                }
            });
        },
        //重置配置
        clearSetting(){
            this.setting={};
            this.fileSetting={};
        },
        //根据资源库获取作业
        setDatabase(value){
            if(!value){
                this.jobTree=[];
            }else {
                SysKettleDefApi.getJobs(value).then(res=>{
                    if(res.success){
                        this.jobs=res.data;
                        this.jobTree=this.aryToTree(res.data,"id","parent");
                    }
                });
            }
        },
        //构建树状数据
        convertData(val, treeData) {
            for (var i = 0; i < treeData.length; i++) {
                if (val == treeData[i].value) {
                    var obj = {
                        label: treeData[i].label,
                        value: treeData[i].value,
                    };
                    if (this.mode == "multiple") {
                        this.selectData.push(obj);
                    } else {
                        this.selectData = obj;
                    }
                }
                if (treeData[i].children) {
                    this.convertData(val, treeData[i].children);
                }
            }
        },
        //将资源库转为树状数据
        aryToTree(ary, idKey, pidKey){
            var obj = {};
            for (var i = 0; i < ary.length; i++) {
                var o = ary[i];
                obj[o[idKey]] = ary[i];
            }
            var rtnAry = [];
            //类型
            var type=this.mdl.type;
            for (var i = 0; i < ary.length; i++) {
                var json = ary[i];
                //非目录且类型不相等则去除
                if(json.type && json.type!=type ){
                    continue;
                }
                if(!json.lasted || !json.type){
                    json.selectable=false;
                }else {
                    json.selectable=true;
                }
                var id = json[idKey];
                var pid = json[pidKey];
                if (obj[pid] && id != pid) {
                    var parent = obj[pid];
                    parent.children = parent.children || [];
                    parent.children.push(json);
                } else {
                    rtnAry.push(json);
                }
            }
            return rtnAry;
        },
        //上传文件
        selectFile(){
            var self = this;
            var inputFile = document.getElementById('inputid');
            var file=inputFile.files[0];
            const formData = new FormData();
            formData.append('file', file);
            SysKettleDefApi.uploadFile(formData).then(res => {
                if (res.success) {
                    self.fileSetting={
                        fileName:file.name,
                        fileId:res.data.fileId
                    }
                }else {
                    self.fileSetting={};
                }
            });
        },
        //资源库选择作业后获取目录结构
        jobChange(value){
            for (var i = 0; i < this.jobs.length; i++) {
                if(this.jobs[i].text==value){
                    this.setting.directory=this.getDirectory(this.jobs[i].parent);
                    break;
                }
            }
        },
        //获取目录结构
        getDirectory(parentId){
            for (var i = 0; i < this.jobs.length; i++) {
                if(this.jobs[i].id==parentId){
                    return this.jobs[i].path;
                }
            }
            return "/";
        },
        onSelectChange(selectedRowKeys) {
            this.selectedRowKeys = selectedRowKeys;
        },
        //新增参数
        addParame(){
            this.parameterList.push({
                idx_:Util.randomId(),
                name:"",
                value:""
            });
        },
        //删除参数
        removeParames(){
            this.removeRows(this.parameterList, this.selectedRowKeys);
        }
    },
    watch:{
        "setting.database":function (val,oldVal){
            this.setDatabase(val);
        },
        "mdl.storeSetting":function (val){
            if(val){
                var obj = JSON.parse(val);
                if(this.mdl.storeType=="database"){
                    this.setting=obj;
                }else if(this.mdl.storeType=="file"){
                    this.fileSetting=obj;
                }
            }
        },
        "mdl.parameters":function (val,oldVal){
            if(val){
                var ary = JSON.parse(val);
                for (var i = 0; i < ary.length; i++) {
                    ary[i].idx_=Util.randomId();
                }
                this.parameterList=ary;
            }
        }
    }
}
</script>
<style>
.ainpust{
    position: relative;
}
#inputid{
    position: absolute;
    top: 0px;
    left: 0px;
    opacity: 0;
    z-index: -1;
}
.relick a {
    margin-right: 10px;
}

</style>
